package il.adscan;

import il.adscan.domain.Advertisement;
import il.adscan.exception.ParsingException;
import il.adscan.scan.json.impl.WinWinScanner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Scanner {

    public static List<Advertisement> scanAllSites() throws IOException {
//        ScanRunner[] scanRunners = {
//                new ScanRunner(1, 1, adScanner),
//                new ScanRunner(2, 2, new WinWinScanner()),
//                new ScanRunner(3, 3, new WinWinScanner())
//        };

        int lastPageNumber = new WinWinScanner().getLastPageNumber();

        List<Advertisement> advertisements = new ArrayList<>();
        for (int pageNumber = 1; pageNumber < lastPageNumber; pageNumber+=50) {
            List<Advertisement> advertisementList = parsePart(pageNumber);
            if (advertisementList.isEmpty()) {
                return advertisements;
            }
            advertisements.addAll(advertisementList);
        }
        System.out.println("Number of advertisements: " + advertisements.size());
        return advertisements;
    }

    private static List<Advertisement> parsePart(int pageNumber) {
//        int lastPageNumber = 1;
//        try {
//            lastPageNumber = adScanner.getLastPageNumber();
//        } catch (IOException e) {
//            e.printStackTrace();
//            throw new ParsingException(e.getMessage(), e);
//        }
        List<ScanRunner> scanRunners = new ArrayList<>();
        for (int i = pageNumber; i < pageNumber + 50; i++) {
            scanRunners.add(new ScanRunner(i, i, new WinWinScanner()));
        }
        List<Future<Set<Advertisement>>> advertisementList = new ArrayList<>();
        ExecutorService executorService = Executors.newFixedThreadPool(50);
        for (ScanRunner scanRunner : scanRunners) {
            advertisementList.add(executorService.submit(scanRunner));
        }
        List<Advertisement> advertisements = new ArrayList<>();
        try {
            for (Future<Set<Advertisement>> future : advertisementList) {
                advertisements.addAll(future.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            throw new ParsingException(e.getMessage(), e);
        }
        executorService.shutdown();
        return advertisements;
    }
}
